import React from 'react';
import { Modal, Form, Checkbox , Button, Select, TimePicker, message  } from 'antd';
import moment from 'moment';
import { FormInstance } from 'antd/lib/form';
import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  typeDisabled:string;
  disabledTimeList:[];
  values:string;
  onSubmit: (values:any) =>void;
  onCancel: () => void;
}

const { Option } = Select;

const { RangePicker } = TimePicker;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 10 },
};
const tailLayout = {
  wrapperCol: { offset: 4, span: 16 },
};

const options = [
  { label: '星期一', value: 'Monday' },
  { label: '星期二', value: 'Tuesday' },
  { label: '星期三', value: 'Wednesday' },
  { label: '星期四', value: 'Thursday' },
  { label: '星期五', value: 'Friday' },
  { label: '星期六', value: 'Saturday' },
  { label: '星期日', value: 'Sunday' },
];

const initLocalDate = () =>{
  let array = [];
  for(var i = 1; i<=31;i++){
    array.push(i);
  }
  return array;
}
//日期选择重排，从小到大
const sortNumber = (a:number,b:number) =>{
  return a - b
}

const planTime = new Object();

class FormContent extends React.Component {
  constructor(props: any) {
    super(props);
    this.state = {
      daysList:[], //每月--几号选择列表
      list:[], //1-31号
    }
  }
  
  formRef = React.createRef<FormInstance>();
 
  //时间重叠校验
  timeCheck = (index:string) =>{
    const parent = this.props.parent;
    const disabledTimeList = parent.disabledTimeList;
    const startTimeArr =[];
    const endTimeArr = [];
    if(index){//每周
      const index1 = parseInt(index);
      startTimeArr.push(disabledTimeList[index1].startTime);
      endTimeArr.push(disabledTimeList[index1].endTime);
    }else{//每天
      for(let i in disabledTimeList){
        startTimeArr.push(disabledTimeList[i].startTime);
        endTimeArr.push(disabledTimeList[i].endTime);
      }
    }
    startTimeArr.push(planTime.startTime);
    endTimeArr.push(planTime.endTime);
    const begin = startTimeArr.sort();
    const over = endTimeArr.sort();
    for(var k=1;k<begin.length;k++){
      if (begin[k] <= over[k-1]){
          return false;
      }
    }
    return true;
  }

  onFinish = (values:any) => {
    const parent = this.props.parent;
    planTime["id"] = parent.values.id;
    if(!planTime["startTime"] || !planTime["endTime"]){
      planTime["startTime"] = values.time[0]._i;
      planTime["endTime"] = values.time[1]._i;
    }
    for(var key in values){
      if(values[key] && key !="time"){
        if(key == "month" && values["month"].length != 0){
          values["month"] = values["month"].sort(sortNumber);
          planTime[key] = values[key];
        }
        if(key != "month"){
          planTime[key] = values[key];
        }
      }    
    }
    //时间重叠校验
    let flag = true;
    let disabledTimeList = parent.disabledTimeList;
    if(disabledTimeList.length > 0){//第一个添加无需校验
      switch(planTime.type){
        case 'day':
          flag = this.timeCheck("");
          if(!flag){
            message.warn("时间段存在重叠！");
          }
          break;
        case 'week':
          const week = planTime.week;
          for(let i in disabledTimeList){
            for(let j in disabledTimeList[i].week){
              for(let k in week){
                if(week[k] == disabledTimeList[i].week[j]){
                  flag = this.timeCheck(i);
                  if(!flag){
                    message.warn(`"${options.find(item=>item.value === week[k]).label}" 时间段存在重叠！`);
                    return false;
                  }
                }
              }
            }
          }
          break;
        case 'month':
          const month = planTime.month;
          for(let i in disabledTimeList){
            for(let j in disabledTimeList[i].month){
              for(let k in month){
                if(month[k] == disabledTimeList[i].month[j]){
                  flag = this.timeCheck(i);
                  if(!flag){
                    message.warn(`"${month[k]}号" 时间段存在重叠！`);
                    return false;
                  }
                }
              }
            }
          }
          break;
        default:
      }
    }
    if(flag){
      planTime["programList"] = parent.values.programList;
      parent.onSubmit(planTime);
    }
  };

  weekSelectChange = () => {
    this.formRef.current?.validateFields();
  }

  onTypeChange = (type:string) =>{ //循环周期select
    if(type == "day"){
      delete planTime.week;
      delete planTime.month;
      this.setState({daysList:[]});
      this.formRef.current?.setFieldsValue({month:[]});
    }else if( type == "week"){
      delete planTime.month;
      this.setState({daysList:[]});
      this.formRef.current?.setFieldsValue({month:[]});
    }else if(type =="month"){
      delete planTime.week;
    }
  }

  dateSelectChange = (id:string) =>{
    const selectedList = this.state.daysList;
    let index = selectedList.indexOf(id);
    if(index > -1){
      selectedList.splice(index,1);
    }else{
      selectedList.push(id);
    }
    this.setState({daysList:selectedList});
    this.formRef.current?.setFieldsValue({month:selectedList});
    this.formRef.current?.validateFields();
  }

  planTimePickChange = (value:any,dateString:string) => { //循环时间段
    if(dateString){
        planTime["startTime"] = dateString[0];
        planTime["endTime"] = dateString[1];
    }
  }
  componentDidMount(){
    this.setState({list:initLocalDate()});
    const values = this.props.parent.values;
    if(values){
      this.formRef.current?.setFieldsValue({
        "time":[moment(values.startTime,"HH:mm:ss"),moment(values.endTime,"HH:mm:ss")]
      });
      planTime["startTime"] = values.startTime;
      planTime["endTime"] = values.endTime;
      if(values.month != undefined){
        this.setState({daysList:values.month});
      }
    }else{
      planTime["startTime"] = "08:00:00";
      planTime["endTime"] = "20:00:00";
    }
  }
  render(){
    const values = this.props.parent.values;
    const typeDisabled = this.props.parent.typeDisabled;
    return (
      <Form 
        {...layout} 
        ref={this.formRef}
        onFinish={this.onFinish}
      >
        <Form.Item name="time" label="循环时间段" rules={[{ required: true }]} className={typeDisabled?styles.cycleTime:null}
          initialValue={[moment("08:00:00","HH:mm:ss"),moment("20:00:00","HH:mm:ss")]}
          >
          <RangePicker showNow onChange={this.planTimePickChange} />
        </Form.Item>
        <Form.Item 
          name="type" 
          label="循环周期" 
          initialValue={values != ""? values.type:(typeDisabled ? typeDisabled:"day")}
          rules={[{ required: true }, {
              validator: (rule, value, callback) => {
                if(value === "week" && 
                  (this.formRef.current?.getFieldValue('week') == undefined
                  || this.formRef.current?.getFieldValue('week').length == 0)
                 ){
                    callback("请选择循环周期");
                }else if(value === "month" && 
                  (this.formRef.current?.getFieldValue('month') == undefined
                  || this.formRef.current?.getFieldValue('month').length == 0)
                 ){
                    callback("请选择循环周期");
                }else{
                  callback();
                }
              },
          },]}>
          <Select defaultValue="day" disabled={typeDisabled? true:false} onChange={this.onTypeChange}>
            <Option value="day">每天</Option>
            <Option value="week">每周</Option>
            <Option value="month">每月</Option>
          </Select>
        </Form.Item>
        <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
            prevValues.type !== currentValues.type
            }   
        >
        {({ getFieldValue }) => {
            return getFieldValue('type') === "week" ? (
            <Form.Item label=" " colon={false} name="week" initialValue={values.week}>
                <Checkbox.Group options={options} onChange={this.weekSelectChange} />
            </Form.Item>
            ) : null;
        }}
        </Form.Item>
        <Form.Item hidden={true} name="month" initialValue={values.month}>
        </Form.Item>
        <Form.Item
            {...tailLayout}
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
            prevValues.type !== currentValues.type
            }   
        >
        {({ getFieldValue }) => {
            return getFieldValue('type') === "month" ? (
            <Form.Item label=" "  colon={false}>
                <div className={styles.calendarList}>
                  <ul>
                    {this.state.list.map((item,index) => 
                      <li key={item} className={this.state.daysList.indexOf(item)>-1 ? "selected":""} onClick={()=>this.dateSelectChange(item)}><span>{item}</span></li>
                    )} 
                  </ul>
                </div>
            </Form.Item>
            ) : null;
        }}
        </Form.Item>
        <Form.Item {...tailLayout} className={styles.footer}>
          <Button type="primary" htmlType="submit">
            确定
          </Button>
          <Button htmlType="button"  style={{marginLeft:50}} onClick={this.props.parent.onCancel}>
            取消
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

const SetPlayTimeModel: React.FC<CreateFormProps> = (props) => {

  const { modalVisible, typeDisabled, disabledTimeList, values, onSubmit, onCancel } = props;
  return (
    <Modal
      destroyOnClose
      title="设置播放时间段"
      visible={modalVisible}
      onSubmit={() => onSubmit(values)}
      onCancel={() => onCancel()}
      footer={null}
    >
      <FormContent parent={props} />
    </Modal>
  );
};

export default SetPlayTimeModel;
